from datetime import date
from flask import Blueprint,request,jsonify
import requests
from requests.api import post
from requests.sessions import Request
#密码加密
from werkzeug.security import generate_password_hash,check_password_hash
from conf.comm import sqlalchemy_context
from database import *
import json
import re
import random
from utils.comm import send_message
from utils.redisconn import r
from utils.myjwt import myjwt
#蓝图初始化
bp_users = Blueprint('users',__name__)

#注册功能实现
@bp_users.route('/reg',methods=['POST'])
@sqlalchemy_context()
def reg():
    #获取用户输入
    data = request.data
    if not data:
        data = request.form
    else:
        data = json.loads(data)
    #有效性验证，正则验证手机号
    reg = re.match('^1[3-9]\d{9}$',data['mobile'])
    if not reg:
        return jsonify({"code":10012,'mes':'手机号不合法'})
    #构造user
    try:
         user = User(username=data['username'],password=generate_password_hash(data['password']),mobile=data['mobile'])
         db.session.add(user)
         db.session.commit()
         return jsonify({"code":200})
    except:
        return jsonify({"code":10010}) 

#发送验证码
@bp_users.route('/sendsms',methods=['POST'])
def sendsms():
    #传递手机号
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    mobile = data['mobile']
    #有效性验证，正则验证手机号
    reg = re.match('^1[3-9]\d{9}$',data['mobile'])
    if not reg:
        return jsonify({"code":10012,'mes':'手机号不合法'})
    # 验证是否30秒内已经发过验证码
    code = r.get_str(mobile)
    if code:
        return jsonify({'code':10015,'mes':'30秒内您已经发送过验证码了'})
    #生成验证码
    code = str(random.randint(100000,999999))
    #调用短信接口
    flag = send_message(mobile,code,1)#验证是否30秒内已经发过验证码
    code  = r.get_str(mobile)
    if flag:
        #发送成功，存入redis
        r.set_str(mobile,code,60)
        #返回结果（验证码）
        return jsonify({'code':200,'smscode':code})
    else:
        return jsonify({'code':20011,'mes':'发送失败，请重试'})
    
   
@bp_users.route('/login',methods=['POST'])
def login():
    #获取用户输入
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    mobile = data['mobile']
    #用户输入的验证码
    code = data['code']
    # 通过手机号redis查
    rcode = r.get_str(mobile)
    # 存在值对比-》
    if rcode:
        if int(code) == int(rcode):
            # 用手机号生成一个新用户
            user = User.query.filter_by(mobile=mobile).first()
            #用户不存在添加
            if not user:
                user = User(username=mobile,mobile=mobile)
                db.session.add(user)
                db.session.commit()
                #清除redis
            r.del_str(mobile)
            # 返回结果（pyjwt生成token）
            return jsonify({"code":200,'userid':user.id,'username':user.username})
        else:
            #不存在返回
            return jsonify({"code":20013,'mes':'验证码错误，请重新输入'})
    else:
	    #不存在返回
        return jsonify({"code":20012,'mes':'验证码不存在，请重新发送'})



@bp_users.route('/getuserinfo',methods=['POST'])
def getuserinfo():
    # 获取token
    try:
        token = request.headers['Token']
    except:
        return jsonify({'code':403,'mes':'请传递token'})
    # 解密重新生成token
    newtoken = myjwt.jwt_decode(token)
    if newtoken and myjwt.check(token,newtoken):
        # 数据库查询返回
        id = request.args.get('userid')
        User.query.filter_by(id=id).first()
        return 'ok'
    else:
        return jsonify({'code':403,'mes':'无权访问'})




# @bp_users.route('/login1',methods=['post'])
# def login():
#     date = request.data
#     if date:
#         date = json.loads(date)
#     else:
#         date = request.form
#         return jsonify({'code':30010,'mes':'输入不能为空'})
#     username = date['username']
#     password = date['password']
#     user = User.query.filter_by(username=username).first()
#     if username==user.username:
#         if password==user.password:
#             return jsonify({'code':200,'userid':user.user.id,'username':user.username})
#         else:
#             return jsonify({'code':30011,'mes':'密码错误'})
#     else:
#         return jsonify({'code':30012,'mes':'用户不存在'})
        